package com.theyeasy.dvmini.weixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.theyeasy.weixin.model.WxMiniSessionInfo;
import org.theyeasy.weixin.service.WxMiniService;
import org.theyeasy.weixin.util.WxMiniUtil;

import com.google.common.base.Strings;
import com.theyeasy.dvmini.model.Articles;
import com.theyeasy.dvmini.model.Fans;
import com.theyeasy.dvmini.model.Remarks;
import com.theyeasy.dvmini.model.Sales;
import com.theyeasy.dvmini.pc.controller.BaseController;
import com.theyeasy.dvmini.service.ArticleService;
import com.theyeasy.dvmini.service.FansService;
import com.theyeasy.dvmini.service.PosterService;
import com.theyeasy.dvmini.service.RemarksService;
import com.theyeasy.dvmini.service.SalesService;
import com.theyeasy.dvmini.util.PageResults;
import com.theyeasy.dvmini.util.StringUtil;
import com.theyeasy.dvmini.vo.Vo_msg;

@Controller
@RequestMapping("/wxmini")
public class WxMiniController extends BaseController {

    @Autowired
    FansService fansService;

    @Autowired
    PosterService posterService;
    @Autowired
    WxMiniService wxMiniService;

    @Autowired
    SalesService salesService;
    
    @Autowired
    RemarksService remarkService;
    
    @Autowired
    ArticleService articleService;

    @RequestMapping("/wxmsg")
    public void WxMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        PrintWriter out = response.getWriter();
        if (!WxMiniUtil.checkSignature(signature, timestamp, nonce)) {
            out.print("sorry,该方法只处理微信推送的消息!");
            System.out.println("sorry,该方法只处理微信推送的消息!");
            out.close();
            return;

        }

        // 微信消息接入验证echostr
        if (null != echostr && echostr.length() > 0) {
            System.out.println("check ok,echostr=" + echostr);
            out.print(echostr);
            out.close();
            return;
        }

        // 处理用户发送来的消息
        WxMiniUtil wxMiniUtil = new WxMiniUtil();
        String responseMsg = wxMiniService.processRequest(request);
        if (null == response || responseMsg.length() <= 0)
            responseMsg = "success";

        // 响应微信服务器
        out.print(responseMsg);
        out.close();

        System.out.println("回复给微信的消息：" + responseMsg);

    }

    @RequestMapping("/login") // 购房助手登录 double lng,double lat
    public @ResponseBody Vo_msg login(@RequestParam(value = "code") String code,
            @RequestParam(value = "shareFansId") Integer shareFansId,
            @RequestParam(value = "saleId") Integer saleId,
            @RequestParam(value = "nickname") String nickname,
            @RequestParam(value = "logo") String logo,
            @RequestParam(value="lng") double lng,
            @RequestParam(value="lat") double lat
    		) {
        logger.info("小程序登录：code=" + code);
        // 取openid
        WxMiniSessionInfo sessionInfo = WxMiniUtil.jscode2session(code);
        // 添加粉丝记录
        Fans fans = fansService.addFans(sessionInfo, shareFansId, nickname, logo,saleId,lng,lat);
        if (fans != null) {
            String salephone = "13712218619";//默认电话
            if (!StringUtil.isZearoOrNull(fans.getSalesid())) {

                Sales sale = salesService.getSales(fans.getSalesid());
                if (sale != null && !Strings.isNullOrEmpty(sale.getPhone()))
                    salephone = sale.getPhone();
            }

            Map<String, Object> map = new HashMap<>();
            map.put("fansid", fans.getId());
            map.put("saleid", fans.getSalesid());
            map.put("salephone", salephone);
            map.put("miniOpenId", sessionInfo.getOpenid());
            return new Vo_msg(0, map);
        } else {
            return new Vo_msg(-1, "登录失败，服务器异常");
        }
    }

    // 获取小程序二维码码1
    @RequestMapping(value = "/getminicode1", method = RequestMethod.POST)
    public @ResponseBody Vo_msg getMiniCode1(String path, int width) {
        String result = WxMiniUtil.getMiniCode1(path, width, true, 0, 0, 0);
        return new Vo_msg(0, result);
    }

    // 获取小程序二维码码2
    @RequestMapping(value = "/getminicode2", method = RequestMethod.POST)
    public @ResponseBody Vo_msg getMiniCode2(String scene, String page, int width) {
        try {
            scene = URLEncoder.encode("lcc", "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String result = WxMiniUtil.getMiniCode2(scene, page, width, true, 0, 0, 0);
        return new Vo_msg(0, result);
    }

    // 获取小程序二维码码1
    @RequestMapping(value = "/getminicode3", method = RequestMethod.POST)
    public @ResponseBody Vo_msg getMiniCode3(String path, int width) {
        String result = WxMiniUtil.getMiniCode3(path, width);
        return new Vo_msg(0, result);
    }

    // 强制刷新Token
    @RequestMapping(value = "/refresh_token")
    public @ResponseBody String refreshToken(String pwd) {
        if (!pwd.equals("nmdzpsmhs"))
            return "error pwd";
        return WxMiniUtil.refreshToken();
    }

    // 生成海报
    @RequestMapping(value = "/generatePoster", method = RequestMethod.POST)
    public @ResponseBody Vo_msg generatePoster(Integer saleid) {
        Vo_msg msg = posterService.GeneratePosterJPG(saleid);
        return msg;
    }


    // 增加电话记录
    @RequestMapping(value = "/addCallLog", method = RequestMethod.POST)
    public @ResponseBody Vo_msg addCallLog(Integer fansid, Integer saleid,String projectname) {
        String result = fansService.addCallLog(fansid, saleid,projectname);
        if (result.equals("ok")) {
            return new Vo_msg(0, "保存成功");
        } else {
            return new Vo_msg(-1, result);
        }
    }
    
    //添加楼盘评论
    @RequestMapping(value = "/addRemark", method = RequestMethod.GET)
    public @ResponseBody Vo_msg addRemark(Integer fansid, Integer estateid,String content) {
        String result =remarkService.addRemark(fansid, content, estateid);
        if (result.equals("ok")) {
            return new Vo_msg(0, "保存成功");
        } else {
            return new Vo_msg(-1, result);
        }
    }
    
    //查询楼盘的评论信息
    @RequestMapping(value = "/getRemarksList", method = RequestMethod.GET)
    public @ResponseBody Object getRemarksList(Integer page, Integer pagesize,Integer estateid) {
     return new Vo_msg(0,remarkService.getRemarksList(page, pagesize, estateid, ""));    
    }
    
     //文章列表
    @RequestMapping(value = "/getArticlesList")
    @ResponseBody
    public Object getArticlesList(Integer page,Integer pagesize) {
     
        return new Vo_msg(0,articleService.getArticlesList(page, pagesize, ""));
    }
    
    //增加文章浏览数
    @RequestMapping(value = "/addArticleViewCount")
    @ResponseBody
    public Object addArticleViewCount(Integer id) {
        articleService.addArticleViewCount(id);
        return new Vo_msg(0,"ok");
    }
    
    // 获取
    @RequestMapping(value = "/getArticle")
    @ResponseBody
    public Object getArticle(Integer id) {
    Articles article =articleService.getArticle(id);
        if (article != null) {
            return new Vo_msg(0, article);
        } else {
            return new Vo_msg(-1, "获取失败，数据为空");
        }
    }
    
}
